//
//  RefreshRequestViewController.m
//  UESTCPioneer
//
//  Created by Sway on 14-3-28.
//  Copyright (c) 2014年 Sway. All rights reserved.
//

#import "RefreshRequestViewController.h"
#import "PioneerNewsEntity.h"
#import "UPTitleCell.h"
#import "UPMainInfoCell.h"
#import "UPFooterCell.h"


#import "NewsDetailViewController.h"

static NSString *customTitleCellIndentifier = @"CustomTitleCellIndentifier";
static NSString *customMainCellIndentifier = @"CustomMainCellIndentifier";
static NSString *customFooterCellIndentifier = @"CustomFooterCellIndentifier";
@interface RefreshRequestViewController ()<UPMainInfoCellDelegate,UPTitleCellDelegate,UPFooterCellDelegate>{
    
    NSMutableDictionary *_cellHeightDictionary;
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;


@end

@implementation RefreshRequestViewController


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(void)_initRequestRequireEntityName:(NSString*)EntityName EntityMapping:(NSDictionary*)EntityMapping RequestData:(NSDictionary*)RequestData CommentListRequestData:(NSDictionary*)CommentListRequestData CommentWriteRequestData:(NSDictionary*)CommentWriteRequestData CommentIdKey:(NSString*)CommentIdKey CommentContentKey:(NSString*)CommentContentKey CommentListKeyMapping:(NSDictionary*)CommentListKeyMapping{
    
    entityName=EntityName;
    entityMapping=EntityMapping;
    requestData=RequestData;
    //请求评论列表用的参数
    commentListRequestData=CommentListRequestData;
    //写评论请求用的参数
    commentWriteRequestData=CommentWriteRequestData;
    commentIdKey=CommentIdKey;
    commentContentKey=CommentContentKey;
    commentListKeyMapping=CommentListKeyMapping;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    [self.tableView registerClass:[UPTitleCell class] forCellReuseIdentifier:customTitleCellIndentifier];
    [self.tableView registerClass:[UPMainInfoCell class] forCellReuseIdentifier:customMainCellIndentifier];
    [self.tableView registerClass:[UPFooterCell class] forCellReuseIdentifier:customFooterCellIndentifier];
    
    _cellHeightDictionary=[[NSMutableDictionary alloc]init];
    
    //@AGPhotoBrowser
    AGPhotoBrowserView *photoBrowser = [[AGPhotoBrowserView alloc]init];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - refresh request

-(void)pullDownRefresh:(MJRefreshBaseView *)refreshView{
    [PublicMethod ClearEntity:entityName];
    [NetworkCenter RKRequestWithData:requestData EntityName:entityName Mapping:entityMapping SuccessBlock:^(NSArray *resultArray) {
        NSMutableArray *dic = [[NSMutableArray alloc]init];
        [dic addObjectsFromArray:resultArray];
        tableViewEntitiesArray=[[NSArray alloc]initWithArray:dic];
        
        /*修改*/
        if (self.isPartyActivity) {
            for (NSInteger i = 0; i < tableViewEntitiesArray.count;i++ ) {
                NewsEntity *entity= tableViewEntitiesArray[i];
                entity.newsBody = [NSString stringWithFormat:@"[%@]\n%@",entity.titleBody,entity.newsBody];
            }
        }
        
        /*活动分享：添加分享活动标题*/
        if (self.isMoodShare) {
            for (NSInteger i = 0; i < tableViewEntitiesArray.count;i++ ) {
                MoodShareNewsEntity *entity= tableViewEntitiesArray[i];
                entity.newsBody = [NSString stringWithFormat:@"[%@]\n%@",entity.eventTitle,entity.newsBody];
            }
        }
        /*修改*/
        
        [self.tableView reloadData];
        PullUpRefreshTimes=0;
        [refreshView endRefreshing];
    } failure:^(NSError *error) {
        //        NSLog(@"%@ 下拉请求失败",entityName);
        [refreshView endRefreshing];
        [Alert showAlert:@"刷新失败!"];
        
    }];
}

-(void)pullUpRefresh:(MJRefreshBaseView *)refreshView{
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]initWithDictionary:requestData];
    [dic setObject:[NSString stringWithFormat:@"%d",PullUpRefreshTimes+2] forKey:@"page"];
    
    [NetworkCenter RKRequestWithData:dic EntityName:entityName Mapping:entityMapping SuccessBlock:^(NSArray *resultArray) {
        //
        //        for (PioneerNewsEntity* entity in tableViewEntitiesArray){
        ////            NSLog(@"%@",entity.titleBody);
        //        }
        
        if ([resultArray count]==0){
            [refreshView endRefreshing];
            return ;
        }
        /*修改*/
        
        
        if (self.isPartyActivity) {
            for (NSInteger i = 0; i < resultArray.count;i++ ) {
                NewsEntity *entity= resultArray[i];
                entity.newsBody = [NSString stringWithFormat:@"[%@]\n%@",entity.titleBody,entity.newsBody];
            }
        }
        
        /**/
        
        /*活动分享：添加分享活动标题*/
        if (self.isMoodShare) {
            for (NSInteger i = 0; i < resultArray.count;i++ ) {
                MoodShareNewsEntity *entity= resultArray[i];
                entity.newsBody = [NSString stringWithFormat:@"[%@]\n%@",entity.eventTitle,entity.newsBody];
                //                NSLog(@"entity.newsBody = %@",entity.newsBody);
            }
        }
        /*修改*/
        NSMutableArray *newArray = [[NSMutableArray alloc]init];
        [newArray addObjectsFromArray:tableViewEntitiesArray];
        [newArray addObjectsFromArray:resultArray];
        NSArray *result = [[NSArray alloc]initWithArray:newArray];
        
        
        tableViewEntitiesArray=result;
        
        //        [PublicMethod ClearEntity:entityName];
        [self.tableView reloadData];
        
        //清除core data 因为现在还没有适合下拉刷新和适合本地缓存的api
        
        [refreshView endRefreshing];
        PullUpRefreshTimes++;
        
    } failure:^(NSError *error) {
        //        NSLog(@"%@ 上拉error:%@",entityName,error);
        [Alert showAlert:@"刷新失败！"];
        [refreshView endRefreshing];
    }];
}

-(void)commentButtonPress:(commentButton*)button{
    
    if ([constant checkAccount]) {
        //注册用户无评论权限
        [Alert showAlert:@"对不起,权限不足!"];
        return;
    }
    
    commentViewController *comment = [[commentViewController alloc]init];
    
    
    //    1）type：writeShareComment  （2）user_id：用户的账号
    //    （3）username：用户姓名      （4）shareId：活动分享的id
    //    （5）comment：评论的内容
    
    
    //请求评论列表用的参数
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]initWithDictionary:commentListRequestData];
    [dic setObject:[NSString stringWithFormat:@"%d",button.theId] forKey:commentIdKey];
    commentListRequestData=[[NSDictionary alloc]initWithDictionary:dic];
    
    NSMutableDictionary *temp = [[NSMutableDictionary alloc]initWithDictionary:commentWriteRequestData];
    [temp setObject:[NSString stringWithFormat:@"%d",button.theId] forKey:commentWriteIdKey];
    commentWriteRequestData=[[NSDictionary alloc]initWithDictionary:temp];
    
    
    comment.commentListRequestData=commentListRequestData;
    //写评论请求用的参数
    comment.commentRequestData=commentWriteRequestData;
    comment.commentContentKey=commentContentKey;
    comment.commentListKeyMapping=commentListKeyMapping;
    comment.numberOfComment=[button.titleLabel.text integerValue];
    comment.commentFlag = commentFlag;
    
    [self.leveyTabBarController.navigationController pushViewController:comment animated:YES];
}

#pragma mark - 全文按钮事件

//代理函数
-(void)WholeNewsButtonClick_1:(NSInteger)theId{
    NSLog(@"whole click 1111");
    NewsEntity *entity = [PublicMethod entity:kNewsEntityName WithId:theId];
    
    NSString *content=entity.newsBody;
    NSString *title = entity.titleBody;
    UIViewController *viewController = [[UIViewController alloc]init];
    
    
    UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(viewController.view.frame.origin.x, viewController.view.frame.origin.y, viewController.view.frame.size.width, 40)];
    label.text = title;
    [viewController.view addSubview:label];
    
    //    NSLog(@"执行了label = %@",label);
    UITextView *textView = [[UITextView alloc]initWithFrame:CGRectMake(0, 40,viewController.view.frame.size.width , viewController.view.frame.size.height-40)];
    [textView setText:content];
    [textView setEditable:NO];
    [textView setScrollEnabled:YES];
    [textView setFont:[UIFont systemFontOfSize:18]];
    [viewController.view addSubview:textView];
    
    [self.leveyTabBarController.navigationController pushViewController:viewController animated:YES];
}

-(BOOL)ScreenTouch{
    return NO;
}
//------------ Sakura-2014-10-09 begin 修改-------------
-(void)WholeNewsButtonClick:(NSInteger)theId{
    if(!(dropDown == nil)) {
        [dropDown hideDropDown:dropbtn];
        [self rel];
        return;
    }
    NewsEntity *entity = [PublicMethod entity:kNewsEntityName WithId:theId];
    NSDictionary *tempdic = entity.picUrl;
    NSMutableArray *temparr = [[NSMutableArray alloc] init];
    if (tempdic.count >0) {
        for (int i = 0; i <tempdic.count; i++) {
            temparr[i] = [tempdic objectForKey:[NSString stringWithFormat:@"%i",i]];
        }
    }
    NSString *title = entity.titleBody;
    if (self.isPartyNotice) {
        PartyNoticeNewsEntity *partyEntity = [PublicMethod entity:kPartyNoticeNewsEntityName WithId:theId];
        title = partyEntity.comfrom;
    }
    if (self.isMoodShare) {
        MoodShareNewsEntity *moodEntity = [PublicMethod entity:kMoodShareNewsEntityName WithId:theId];
        title = moodEntity.eventTitle;
    }
    NewsDetailViewController *newContr = [[NewsDetailViewController alloc] initWithImgUrlArr:temparr title:title content:entity.newsBody];
    
    [self.leveyTabBarController.navigationController pushViewController:newContr animated:YES];
}
//------------ Sakura end ---------------


//-(void)WholeNewsButtonClick:(NSInteger)theId{
//    BOOL result = [self ScreenTouch];
//    if (result) {
//        return;
//    }
//    NewsEntity *entity = [PublicMethod entity:kNewsEntityName WithId:theId];
//
//    if (self.isPioneer) {
//        NSDictionary *tempdic = entity.picUrl;
//        NSMutableArray *temparr = [[NSMutableArray alloc] init];
//        if (tempdic.count >0) {
//            for (int i = 0; i <tempdic.count; i++) {
//                temparr[i] = [tempdic objectForKey:[NSString stringWithFormat:@"%i",i]];
//            }
//        }
//        NewsDetailViewController *newContr = [[NewsDetailViewController alloc] initWithImgUrlArr:temparr title:entity.titleBody content:entity.newsBody];
//
//        [self.leveyTabBarController.navigationController pushViewController:newContr animated:YES];
//
//        return;
//    }
//    NSString *content;
//    if (self.isPartyActivity||self.isMoodShare) {
//        NSRange range;
//        range = [entity.newsBody rangeOfString:@"]"];
//        if (range.location != NSNotFound) {
//            content = [entity.newsBody substringFromIndex:range.location+2];
//        }else{
//        }
//    }else{
//        content =entity.newsBody;
//    }
//    UIViewController *viewController = [[UIViewController alloc]init];
//    [viewController.view setFrame:self.view.frame];
//    [viewController.view setBackgroundColor:[UIColor colorWithRed:232.0f/255.0f green:232.0f/255.0f blue:232.0f/255.0f alpha:1.0f]];
//    UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(viewController.view.frame.origin.x, viewController.view.frame.origin.y, viewController.view.frame.size.width, 45)];
//    NSString *title = entity.titleBody;
//    label.text = title;
//    [label setBackgroundColor:[UIColor colorWithRed:232.0f/255.0f green:232.0f/255.0f blue:232.0f/255.0f alpha:1.0f]];
//    [label setFont:[UIFont systemFontOfSize:17]];
//    label.textAlignment = NSTextAlignmentCenter;
//    label.numberOfLines = 0;
//    label.adjustsFontSizeToFitWidth = YES;
//    [viewController.view addSubview:label];
//    [label setTranslatesAutoresizingMaskIntoConstraints:NO];
//    [viewController.view addConstraint:[NSLayoutConstraint constraintWithItem:label
//                                                                    attribute:NSLayoutAttributeTop
//                                                                    relatedBy:NSLayoutRelationEqual
//                                                                       toItem:viewController.view
//                                                                    attribute:NSLayoutAttributeTop
//                                                                   multiplier:1 constant:0]];
//    [viewController.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-3.0-[label]-3.0-|" options:0 metrics:Nil views:NSDictionaryOfVariableBindings(label)]];
//    [viewController.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[label(==45)]" options:0 metrics:Nil views:NSDictionaryOfVariableBindings(label)]];
//    UITextView *textView = [[UITextView alloc]init];
//    [textView setText:content];
//    [textView setEditable:NO];
//    [textView setScrollEnabled:YES];
//    [textView setFont:[UIFont systemFontOfSize:17]];
//    [textView setBackgroundColor:[UIColor colorWithRed:232.0f/255.0f green:232.0f/255.0f blue:232.0f/255.0f alpha:1.0f]];
//    [viewController.view addSubview:textView];
//    [textView setTranslatesAutoresizingMaskIntoConstraints:NO];
//    [viewController.view addConstraint:[NSLayoutConstraint constraintWithItem:textView
//                                                                    attribute:NSLayoutAttributeTop
//                                                                    relatedBy:NSLayoutRelationEqual
//                                                                       toItem:label
//                                                                    attribute:NSLayoutAttributeBottom
//                                                                   multiplier:1
//                                                                     constant:0]];
//    [viewController.view addConstraint:[NSLayoutConstraint constraintWithItem:textView
//                                                                    attribute:NSLayoutAttributeBottom
//                                                                    relatedBy:NSLayoutRelationEqual
//                                                                       toItem:viewController.view
//                                                                    attribute:NSLayoutAttributeBottom
//                                                                   multiplier:1
//                                                                     constant:-5]];
//    [viewController.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[textView]|" options:0 metrics:Nil views:NSDictionaryOfVariableBindings(textView)]];
//    [self.leveyTabBarController.navigationController pushViewController:viewController animated:YES];
//}

#pragma mark - tableView Cell dequeue
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    //    NSLog(@"super tableview delegate");
    
    NewsEntity *entity= tableViewEntitiesArray[indexPath.section];
    if (indexPath.row == 0) {
        //6.0后用这种方式更直接，可以省掉if（cell2＝＝nil）的判断   @黄卓越 2014-3-28
        UPTitleCell *cell = [tableView dequeueReusableCellWithIdentifier:customTitleCellIndentifier forIndexPath:indexPath];
        cell.theId=[entity.theId integerValue];
        [cell setTitle:entity.titleBody];
        [cell setTime:entity.timeAndDate];
        
        
        /*修改*/
        cell.indexPath = indexPath;
        /**/
        
        if (self.isMoodShare) {
            [cell setHeadImageEnable:YES];
            //            [cell setHeadImage:(NSString *)entity.picUrl];
        }
        return cell;
    }
    else if (indexPath.row == 1) {
        
        
        //6.0后用这种方式更直接，可以省掉if（cell2＝＝nil）的判断   @黄卓越 2014-3-28
        UPMainInfoCell *cell2 = [tableView dequeueReusableCellWithIdentifier:customMainCellIndentifier forIndexPath:indexPath];;
        NSDictionary *pic=entity.picUrl;
        NSArray *ImageUrlArray=[pic  allValues];
        
        
        NSMutableArray *temp = [[NSMutableArray alloc]init];
        for (NSString *suffix in ImageUrlArray){
            [temp addObject:[baseUrl stringByAppendingString:suffix]];
        }
        
        NSArray *urlArray = [[NSArray alloc]initWithArray:temp];
        
        
        [cell2 setImageUrlArray:urlArray];
        //@cell的高度自适应
        if ([cell2 hasImage])_cellHeightDictionary[@(indexPath.section)]=@(110+imageViewWidth);
        else _cellHeightDictionary[@(indexPath.section)]=@(110);
        [cell2 setNewsBody:entity.newsBody];
        cell2.theId=[entity.theId integerValue];
        cell2.delegate=self;
        return cell2;
    }
    else {
        UPFooterCell * cell3;
        
        cell3 = [tableView dequeueReusableCellWithIdentifier:customFooterCellIndentifier forIndexPath:indexPath];
        
        /*修改*/
        for (UIView * view in  cell3.contentView.subviews) {
            if (view.tag == 100) {
                [view removeFromSuperview];
            }
        }
        /**/
        
        cell3.theId=[entity.theId integerValue];
        cell3.delegate=self;
        
        UIButton *btn1 = (UIButton *)[cell3.contentView viewWithTag:btn1Tag];
        [cell3 setCommentId:[entity.theId integerValue]];
        [cell3 setCommentNum:[entity.numberOfComment integerValue]];
        [cell3 addCommentButtonTaget:self Action:@selector(commentButtonPress:)];
        [btn1 setImage:[UIImage imageNamed:@"read.png"] forState:UIControlStateNormal];
        
        //设置来源于
        if (self.fromSourceEnable) {
            [cell3 setFromSourceStatus:YES fromSource:self.source];
        }
        
        return cell3;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        return 55;
    }
    else if (indexPath.row == 1){
        CGFloat height;
        
        NewsEntity *entity =tableViewEntitiesArray[indexPath.section];
        NSDictionary *picDic= entity.picUrl;
        NSInteger imageNum=[picDic count];
        if (imageNum==0){
            height=110;
        }
        else {
            if (imageNum==1){
                height=110+imageViewWidth+120;
            }
            else if (imageNum==2){
                height=110+imageViewWidth+90;
            }
            else if (imageNum==3){
                height=110+imageViewWidth+60;
            }
            else {
                height=110+imageViewWidth+30;
            }
            
        }
        
        return height;
    }
    else
        return 40;
}

@end
